package cube.utils.web;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cube.io.StreamUtil;
import cube.utils.FileUtil;
import cube.utils.SystemUtil;

/**
 * Web工具
 * 
 * @author abiao
 */
public class WebUtil {

    /**
     * 获取web项目运行时的根目录
     */
    public static String getWebRootPath() {
        if (!isWebEnv()) {
            return null;
        }
        String clzPath = SystemUtil.getClassPath();
        return clzPath.substring(0, clzPath.indexOf("WEB-INF"));
    }

    /**
     * 查看是否为Web环境
     */
    public static boolean isWebEnv() {
        String clzPath = SystemUtil.getClassPath();
        return clzPath != null && clzPath.contains("WEB-INF");
    }

    /**
     * 读取网页内容
     */
    public static String read(String url, final String charset) {
        String text = null;
        try {
            InputStream is = connect(url).getInputStream();
            text = StreamUtil.read(is, charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }

    /**
     * 获取网页连接
     * 
     * @throws IOException
     * @throws MalformedURLException
     */
    public static HttpURLConnection connect(String url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("referer", getReferer(url));
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect();
        return conn;
    }

    /**
     * 将文件下载到指定目录
     */
    public static boolean download(String fileURL, String downloadPath) {
        try {
            InputStream is = connect(fileURL).getInputStream();
            String baseName = FileUtil.getBaseName(fileURL);
            String file = downloadPath + FileUtil.SEP + baseName;
            StreamUtil.write(is, file);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取Referer头
     */
    private static String getReferer(String url) {
        int tail = url.indexOf("/", 7);
        return tail == -1 ? url : url.substring(0, tail);
    }

    /**
     * 检测地址是否为有效网页
     */
    public static boolean isWebPage(String url, int timeout) {
        HttpURLConnection conn = null;
        try {
            URL webURL = new URL(url);
            conn = (HttpURLConnection) webURL.openConnection();
            conn.setConnectTimeout(timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "text/html".equals(conn.getContentType());
    }

    /**
     * 设置网络代理
     */
    public static void setProxy(String ip, int port) {
        System.setProperty("http.proxyHost", ip);
        System.setProperty("http.proxyPort", port + "");
    }
}
